﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using ADSTS_SERVER.Models;
using ADSTS_SERVER.ViewModels;
using ADSTS_SERVER.ViewModels.Tag;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace ADSTS_SERVER.Controllers
{
    /// <summary>
    /// 资源库标签分类
    /// </summary>
    [DynamicApiController]
    public class LnsTagController
    {
        private readonly ILogger<LnsTagController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public LnsTagController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 标签列表
        /// </summary>
        /// <param name="tsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] TagSearchForm tsf)
        {
            //List<Tag> tags = await db.Queryable<Tag>()
            //    .Where(tg => tg.IsActive == 1)
            //    .WhereIF(!string.IsNullOrEmpty(tsf.Content), cg => cg.Name.Contains(tsf.Content))
            //    .ToListAsync();

            List<string> tags = await db.Queryable<ResourcePool>().Distinct().Select(rpm => rpm.TagName).ToListAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                //Data = tags.Adapt<List<TagView>>(),
                Data = tags,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加标签
        /// </summary>
        /// <param name="tsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] TagSaveForm tsf)
        {
            // 如果名称重复提示不让添加
            bool isExist = await db.Queryable<Tag>().Where(tg => tg.Name == tsf.Name).AnyAsync();
            if (isExist) {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "标签名称已存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            Tag tag = await db.Insertable<Tag>(tsf.Adapt<Tag>()).ExecuteReturnEntityAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = tag.Adapt<TagView>(),
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="tdf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] TagDeleteForm tdf) {
            await db.Updateable<Tag>().SetColumns(t => t.IsActive == 0).Where(t => t.Id == tdf.Id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改标签
        /// </summary>
        /// <param name="tuf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] TagUpdateForm tuf) {
            // 如果名称重复提示不让添加
            bool isExist = await db.Queryable<Tag>().Where(tg => tg.Name == tuf.Name).AnyAsync();
            if (isExist)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "标签名称已存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            // 更新tag表name字段
            await db.Updateable<Tag>(tuf.Adapt<Tag>())
                .UpdateColumns(tg => new { tg.Name })
                .ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = tuf,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看标签
        /// </summary>
        /// <param name="tsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] TagShowForm tsf) {
            Tag tag = await db.Queryable<Tag>()
                .InSingleAsync(tsf.Id);
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = tag,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

    }
}
